import React, { PureComponent } from 'react';
import { connect } from 'dva';
import styles from './RoleManager.less';
import { Col, Card, Form, Input, Select, Icon, Button, Modal,Tree,Table,Divider  } from 'antd';
import {intListToString} from '../../common/utils/stringUtils';
import moment from 'moment';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { NewForm } from 're-antd';

const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
var initLoading = false;
var menuTree = {};
const columns = [
  {
    title: '角色id',
    dataIndex: 'roleId',
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
  {
    title: '更新时间',
    dataIndex: 'createTime',
    sorter: true,
    render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
  },
];

@connect(state => ({
  role: state.role,
}))
@Form.create()
export default class RoleManager extends PureComponent {

  state = {
    postVisible: false,
    modalTitle:"修改角色",
    postValue:{},
  };


  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/fetch',
      payload:{pageIndex:1,pageSize:10},
    });
    if(!initLoading){
      dispatch({
        type:'role/judgePermission',
      }).then((permission)=>{
        if(permission.edit||permission.delete){
          columns.push({
              title: '操作',
              filterDropdownVisible: false,
              render: (text, record, index) => (
                <div>
                  <a onClick={() => this.initEditValue(record)} hidden={!permission.edit}>修改</a>
                  <Divider type="vertical" hidden={!permission.edit}/>
                  <a onClick={()=> this.doDelete(record.roleId)} hidden={!permission.delete}>删除</a>
                </div>
              ),
              
          });
        }
      });
      //菜单列表(增改时使用)
      dispatch({
        type: 'menu/fetch',
      }).then((response)=>{
        menuTree = this.renderTreeNodes(response.result);
      });
      initLoading = true;
    }
    
  }

   //设置权限配置的树形返回标签
   renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.menuId} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (<TreeNode title={item.name} key={item.menuId} dataRef={item}></TreeNode>);
    });
  }

  initNewValue = (flag)=>{
    this.changePostVisible(flag);
    this.setState({
      modalTitle:"新建角色",
      postValue:{
        roleId:0,
        menuIdList:[],
      }
    });
  }

  initEditValue = (record)=> {
    this.changePostVisible(true);
    //获取角色权限
    this.props.dispatch({
      type: 'role/fetchRoleMenuIds',
      payload:record.roleId,
    }).then((res) =>{
      this.setState({
        modalTitle:"修改角色",
        postValue:{
          roleId:record.roleId,
          roleName:record.roleName,
          // menuIdList:tempMenuId,
          menuIdList:intListToString(res),
          remark:record.remark,
        }
      });
    }); 
    
  }

    doPost = (value)=>{
      const { dispatch } = this.props;
      return dispatch({
        type: 'role/post',
        payload:value,
      }).then((res) =>{
        this.showResult(res);
        this.changePostVisible();
      });
    }
    

    doDelete = (roleId)=>{
      const { dispatch } = this.props;
      var roleIds = [roleId];
      const isThis = this;//onOk中拿不到this，这里定义一个变量传值
      Modal.confirm({
        title: '删除角色',
        content: '是否删除该角色?',
        onOk() {
          dispatch({
            type: 'role/delete',
            payload:roleIds,
          }).then((res) =>{
              isThis.showResult(res);
              isThis.changePostVisible();   
          });
        },
        onCancel() {},
      });
    }

    changePostVisible = (flag) => {
      if(!!flag===true && this.newform!=undefined){
        this.newform.reset();    
      }
      this.setState({
        postVisible: !!flag,
      });
  }

  权限配置的树形勾选
  treeOnCheck = (checkedKeys) => {
    this.setState({
      postValue:{
        ...this.state.postValue,
        menuIdList:checkedKeys,
      }});      
  }

  //分页
  changePage = (pagination) => {
    this.props.dispatch({
      type: 'role/fetch',
      payload: {
        pageIndex:pagination.current,
        pageSize:pagination.pageSize
      },
    });
  }

  showResult = (response)=>{
    if(response.code===200){
      Modal.success({
        title: '成功',
        content: '成功',
      });
      this.props.dispatch({
        type: 'role/fetch',
        payload: {
          pageIndex:this.props.role.data.pagination.pageIndex,
          pageSize:this.props.role.data.pagination.pageSize
        } ,
      });
    }else{
      Modal.error({
        title: '失败',
        content: '失败',
      });
    }
  }

  render() {
    const { role: { loading, data,permission} } = this.props;
    const { postVisible,postValue,modalTitle } = this.state;

    return (
      <PageHeaderLayout>
      <Card bordered={false}>
        <div className={styles.tableList}>

          <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.initNewValue(true)} hidden={!permission.save} >
                新建
              </Button>
          </div>
            
          <Table
              loading={loading}
              dataSource={data.list}
              columns={columns}
              rowKey={record => record.roleId}
              pagination={data.pagination}
              onChange={this.changePage}
          />
          <Modal
            title={modalTitle}
            visible={postVisible}
            maskClosable={false}
            // onOk={this.doPost}
            onCancel={() => this.changePostVisible()}
            footer={null}
          >
            <NewForm
              wrappedComponentRef={(v) => this.newform = v}
              button={
                [{ text: '确定', type: 'primary', onClick: 'sumbit' },{ text: '取消', onClick: ()=>this.changePostVisible() }]
              }
              onSubmit={(value)=>{
                return this.doPost(value);
              }}
              defaultValue={postValue}
              col={1}
              items={[
                {
                  key: 'roleId',
                  component: <Input hidden={true} disabled={true}/>,
                },
                {
                  rules: [{ required: true, message: '请输入角色名称!' }],
                  key: 'roleName',
                  label: '角色名称',
                  layout:{labelSpan: 5,componentSpan: 15},
                  component: <Input />,
                },
                {
                  key: 'remark',
                  label: '备注',
                  layout:{labelSpan: 5,componentSpan: 15},
                  component: <Input />,
                },
                {
                  key: 'menuIdList',
                  label: '权限配置',
                  layout:{labelSpan: 5,componentSpan: 15},
                  component: <Tree
                          checkable
                          checkedKeys={postValue.menuIdList}
                          onCheck={this.treeOnCheck}
                        >
                          {menuTree}
                        </Tree>,
                },
              ]}
            />
          </Modal>
          
        </div>
      </Card>

    </PageHeaderLayout>
    );
  }
}
